package com.yanxu;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;

import java.nio.charset.Charset;
import java.util.List;

/**
 * @author 折戟沉沙铁未销
 * @version V1.0
 * @date 2023/11/18-2023
 * @Description: 生产者 实现消息发送到指定的queue中
 */
public class ProducerSample02 {
    public static void main(String[] args) {
        DefaultMQProducer producer=new DefaultMQProducer("pg1");
        producer.setNamesrvAddr("192.168.1.31:9876");

        try {
            producer.start();

            String messageTex="{\n" +
                    "  \"id\": 1001,\n" +
                    "  \"type\": \"site\",\n" +
                    "  \"name\": \"Runoob\",\n" +
                    "  \"description\": \"https://www.runoob.com\",\n" +
                    "  \"price\": 2.55\n" +
                    "}\n";
            Message message = new Message("", "", messageTex.getBytes(Charset.defaultCharset()));
            producer.send(message, new MessageQueueSelector() {
                @Override
                public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
                    System.out.println("当前队列数量：" + mqs.size() + ",明细：" + mqs.toString());
                    System.out.println("Message对象：" + msg.toString());
                    int dataId = Integer.parseInt(msg.getKeys());
                    int index = dataId % mqs.size();
                    MessageQueue messageQueue = mqs.get(index);
                    System.out.println("分区队列:" + messageQueue);
                    return messageQueue;
                }
            },null);


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            producer.shutdown();
        }

    }
}